<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click="$router.back()"
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
    >
      <template #action>
        <div @click="onSearch(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="keyword">
      <van-cell
        @click="onSearch(item)"
        icon="search"
        v-for="(item, index) in list"
        :key="index"
      >
        <span v-html="zitigl(item, keyword)">{{ item }}</span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell :title="item" v-for="item in history" :key="item">
        <van-icon name="close" @click="del(item)" />
      </van-cell>
    </van-cell-group>
    <!-- 没有搜索结果提示 图 -->
    <van-empty
      image="error"
      description="描述文字"
      v-if="!keyword && list.length === 0"
    />
  </div>
</template>

<script>
import { getSuggest } from '../../api/search'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '',
      list: [],
      history: JSON.parse(localStorage.getItem('history')) || []
    }
  },
  methods: {
    zitigl(str, key) {
      // console.log(str, key)
      const reg = new RegExp(key, 'gi')
      return str.replace(
        reg,
        (item) => `<span style="color:red">${item}</span>`
      )
    },
    onSearch(item) {
      if (!item) return
      this.history = this.history.filter((v) => item !== v)
      this.history.unshift(item)

      localStorage.setItem('history', JSON.stringify(this.history))
      this.$router.push({
        path: '/search/result',
        query: { item }
      })
    },
    async inputFn() {
      clearTimeout(this.time)
      this.time = setTimeout(async () => {
        if (!this.keyword) {
          return
        }
        const { data: res } = await getSuggest(this.keyword)
        // console.log(res.options)
        if (res.options[0] === null) {
          return (this.list = [])
        }
        this.list = res.options
      }, 300)
    },
    del(item) {
      console.log(item)
      this.history = this.history.filter((v) => item !== v)
      localStorage.setItem('history', JSON.stringify(this.history))
    }
  }
}
</script>

<style lang="less"></style>
